package ubi.com.wifitest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * WIFI视图，显示当前wifi和设备连接信息
 *
 * @author eli chang
 */
public class WifiView extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "WifiView";
    //wifi和设备的七种状态
    public static final int STATE_WIFI_DISABLE = 1;
    public static final int STATE_WIFI_SCANNING = 2;
    public static final int STATE_DEVICE_404 = 3;
    public static final int STATE_DEVICE_CONNECTING = 4;
    public static final int STATE_DEVICE_CONNECTED = 5;
    public static final int STATE_DEVICE_DISCONNECTED = 6;
    public static final int STATE_DEFAULT = 7;

    //六种信息
    public static final String WIFI_DISABLE = "wifi设备已关闭";
    public static final String DEVICE_DISCONNECTED = "设备未连接";
    public static final String DEVICE_CONNECTED = "设备已连接";
    public static final String WIFI_SCANNING = "设备搜索中...";
    public static final String DEVICE_CONNECTING = "搜索到设备，连接中...";
    public static final String DEVICE_404 = "未搜索到设备";

    //字体颜色
    private static final int COLOR_TEXT = 0xff3197ca;
    //可用状态下wifi颜色
    private static final int COLOR_WIFI_ENABLE = 0xff3197ca;
    //不可用状态下wifi颜色
    private static final int COLOR_WIFI_DISABLE = 0xffaaaaaa;

    //当前状态
    private int state = STATE_DEFAULT;

    private Context context;
    private SurfaceHolder surfaceHolder;
    private Paint paint;
    //当前组件宽高
    private int viewWidth;
    private int viewHeight;
    //三条wifi信号的偏移角度
    private int swapAngle1 = 220;
    private int swapAngle2 = 220;
    private int swapAngle3 = 220;
    //绘制线程
    private DrawingThread drawing;

    public WifiView(Context context) {
        this(context, null);
    }

    public WifiView(Context context, AttributeSet attributeSet) {
        this(context, attributeSet, 0);
    }

    public WifiView(Context context, AttributeSet attributeSet, int defStyle) {
        super(context, attributeSet, defStyle);
        this.context = context;

        initial();
    }

    /**
     * 初始化
     */
    private void initial() {
        //初始化SurfaceHolder
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        //初始化画笔
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(COLOR_TEXT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        //获取组件窗口模式和大小
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        //当宽高设置为wrap_content，重新定义其大小
        if (widthSpecMode == MeasureSpec.AT_MOST) {
            widthSpecSize = Util.dip2px(context, 50);
        }
        if (heightSpecMode == MeasureSpec.AT_MOST) {
            heightSpecSize = Util.dip2px(context, 50);
        }
        //将组件设置为正方形，以最小的尺寸为边长
        int mini = Math.min(widthSpecSize, heightSpecSize);
        widthSpecSize = mini;
        heightSpecSize = mini;
        //设置尺寸
        setMeasuredDimension(widthSpecSize, heightSpecSize);
        //标记宽高
        viewWidth = widthSpecSize;
        viewHeight = heightSpecSize;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //当surface被创建后，绘制UI
        notifyDrawThread();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    /**
     * 设置当前显示状态
     *
     * @param state
     */
    public void setState(int state) {
        this.state = state;
        notifyDrawThread();
    }

    /**
     * 提示绘图线程更新状态
     */
    private void notifyDrawThread() {
        try {
            if (drawing != null) {
                drawing.interrupt();
                drawing = null;
            }
            drawing = new DrawingThread();
            drawing.start();
        } catch (Exception e) {
        }
    }

    /**
     * 绘制UI的线程
     */
    private class DrawingThread extends Thread {
        //中断标记
        private boolean interrupted;

        @Override
        public void run() {
            try {
                switch (state) {
                    case STATE_DEFAULT:
                        drawDefault();
                        break;

                    case STATE_WIFI_DISABLE:
                        drawWifiDisable();
                        break;

                    case STATE_WIFI_SCANNING:
                        drawScanning();
                        break;

                    case STATE_DEVICE_404:
                        drawDevice404();
                        break;

                    case STATE_DEVICE_CONNECTING:
                        drawDeviceConnecting();
                        break;

                    case STATE_DEVICE_CONNECTED:
                        drawConnected();
                        break;

                    case STATE_DEVICE_DISCONNECTED:
                        drawDisconnected();
                        break;
                }
            } catch (Exception e) {
                return;
            }
        }

        @Override
        public void interrupt() {
            this.interrupted = true;
            super.interrupt();
        }

        @Override
        public boolean isInterrupted() {
            return interrupted;
        }

        /**
         * 默认视图
         */
        private void drawDefault() {
            try {
                Canvas canvas = surfaceHolder.lockCanvas();
                drawWifi(canvas, 3, null);
                drawInfo(canvas, DEVICE_CONNECTED);
                surfaceHolder.unlockCanvasAndPost(canvas);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * wifi未开启的UI
         */
        private void drawWifiDisable() {
            backToDefault(0, WIFI_DISABLE);
        }

        /**
         * 扫描中...
         */
        private void drawScanning() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(10);

                    int[] angles = {swapAngle1, swapAngle2, swapAngle3};
                    Canvas canvas = surfaceHolder.lockCanvas();
                    drawWifi(canvas, 3, angles);
                    drawInfo(canvas, WIFI_SCANNING);
                    surfaceHolder.unlockCanvasAndPost(canvas);

                    swapAngle1 += 5;
                    swapAngle2 += -5;
                    swapAngle3 += 5;

                    swapAngle1 = reviseAngle(swapAngle1);
                    swapAngle2 = reviseAngle(swapAngle2);
                    swapAngle3 = reviseAngle(swapAngle3);
                } catch (Exception e) {
                    return;
                }
            }
        }

        /**
         * 未找到设备
         */
        private void drawDevice404() {
            backToDefault(0, DEVICE_404);
        }

        /**
         * 设备连接中
         */
        private void drawDeviceConnecting() {
            int count = 3;
            backToDefault(3, DEVICE_CONNECTING);
            while (!isInterrupted()) {
                try {
                    Thread.sleep(220);

                    Canvas canvas = surfaceHolder.lockCanvas();
                    count++;
                    if (count > 3)
                        count = 0;
                    drawWifi(canvas, count, null);
                    drawInfo(canvas, DEVICE_CONNECTING);
                    surfaceHolder.unlockCanvasAndPost(canvas);
                } catch (Exception e) {
                    break;
                }
            }
        }

        /**
         * 设备连接成功
         */
        private void drawConnected() {
            backToDefault(3, DEVICE_CONNECTED);
        }

        /**
         * 未连接到设备
         */
        private void drawDisconnected() {
            backToDefault(0, DEVICE_DISCONNECTED);
        }

        /**
         * wifi弧线回到默认状态
         *
         * @param count
         * @param info
         */
        private void backToDefault(int count, String info) {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(10);

                    if (swapAngle1 != 220) {
                        swapAngle1 += 5;
                        swapAngle1 = reviseAngle(swapAngle1);
                    }
                    if (swapAngle2 != 220) {
                        swapAngle2 += -5;
                        swapAngle2 = reviseAngle(swapAngle2);
                    }
                    if (swapAngle3 != 220) {
                        swapAngle3 += 5;
                        swapAngle3 = reviseAngle(swapAngle3);
                    }
                    int[] angles = {swapAngle1, swapAngle2, swapAngle3};
                    //获取画布
                    Canvas canvas = surfaceHolder.lockCanvas();
                    //绘制
                    drawWifi(canvas, count, angles);
                    drawInfo(canvas, info);
                    //加载画布
                    surfaceHolder.unlockCanvasAndPost(canvas);

                    if (swapAngle1 == 220 && swapAngle2 == 220 && swapAngle3 == 220)
                        break;
                }
            } catch (Exception e) {
            }
        }

        /**
         * 修正角度，处于0-360之间
         *
         * @param angle
         * @return
         */
        private int reviseAngle(int angle) {
            if (angle >= 360)
                angle = 0;
            else if (angle <= 0)
                angle = 360;
            return angle;
        }

        /**
         * 绘制Wifi
         *
         * @param canvas      绘制的画布
         * @param count       激活状态的弧线数目
         * @param startAngles 三个弧线的角度
         * @return
         */
        private Canvas drawWifi(Canvas canvas, int count, int startAngles[]) {
            try {
                if (canvas == null)
                    return null;
                canvas.drawColor(0xffffffff);
                //设置画笔样式
                paint.reset();
                paint.setAntiAlias(true);
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(COLOR_WIFI_ENABLE);
                //设置wifi三条弧线的颜色
                int color1 = COLOR_WIFI_DISABLE;
                int color2 = COLOR_WIFI_DISABLE;
                int color3 = COLOR_WIFI_DISABLE;
                switch (count) {
                    case 1:
                        color1 = COLOR_WIFI_ENABLE;
                        break;
                    case 2:
                        color1 = COLOR_WIFI_ENABLE;
                        color2 = COLOR_WIFI_ENABLE;
                        break;
                    case 3:
                        color1 = COLOR_WIFI_ENABLE;
                        color2 = COLOR_WIFI_ENABLE;
                        color3 = COLOR_WIFI_ENABLE;
                        break;
                    default:
                        break;
                }

                //设置wifi三条弧线的偏移角度
                int startAngle1 = 220;
                int startAngle2 = 220;
                int startAngle3 = 220;
                if (startAngles != null && startAngles.length == 3) {
                    startAngle1 = startAngles[0];
                    startAngle2 = startAngles[1];
                    startAngle3 = startAngles[2];
                }

                //设置wifi中心点位置
                int wifiPointX = viewWidth / 2;
                int wifiPointY = viewHeight / 2;
                //设置每条弧线相对偏移尺寸
                int offset = viewWidth / 8;
                //设置弧线宽度
                int lineWidth = viewWidth / 18;

                //绘制wifi中心点
                canvas.drawCircle(wifiPointX, wifiPointY, (float) (lineWidth * 0.7), paint);

                //重置画笔样式
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(lineWidth);
                paint.setStrokeCap(Paint.Cap.ROUND);

                //绘制最内部弧线
                paint.setColor(color1);
                canvas.drawArc(wifiPointX - offset, wifiPointY - offset, wifiPointX + offset, wifiPointY + offset, startAngle1, 100, false, paint);
                //绘制中间弧线
                paint.setColor(color2);
                canvas.drawArc(wifiPointX - offset * 2, wifiPointY - offset * 2, wifiPointX + offset * 2, wifiPointY + offset * 2, startAngle2, 100, false, paint);
                //绘制最外侧弧线
                paint.setColor(color3);
                canvas.drawArc(wifiPointX - offset * 3, wifiPointY - offset * 3, wifiPointX + offset * 3, wifiPointY + offset * 3, startAngle3, 100, false, paint);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return canvas;
            }
        }

        /**
         * 绘制文字信息
         *
         * @param canvas 画布
         * @param text   信息
         * @return
         */
        private Canvas drawInfo(Canvas canvas, String text) {
            try {
                if (canvas == null)
                    return null;
                //重置画笔
                paint.reset();
                paint.setAntiAlias(true);
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(COLOR_TEXT);
                //设置字体大小
                int textSize = viewWidth / 12;
                paint.setTextSize(textSize);
                //计算文字宽度
                float textWidth = paint.measureText(text);
                //绘制文字
                canvas.drawText(text, (viewWidth - textWidth) / 2, viewHeight - 5, paint);
            } catch (Exception e) {
            } finally {
                return canvas;
            }
        }
    }

    /**
     * 回收资源
     */
    public void destroy() {
        if (drawing != null) {
            drawing.interrupt();
            drawing = null;
        }
        if (surfaceHolder != null) {
            surfaceHolder.removeCallback(this);
        }
        surfaceHolder = null;
        paint = null;
    }
}